package com.huchao.www.utils;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @BelongsProject: background-management-v10
 * @BelongsPackage: com.huchao.www.utils
 * @Author: 亖思
 * @CreateTime: 2023/3/22 11:30
 * @Version: 1.0
 */
@Component
public class SchedulerUtil {

    /**
     * 〈启动〉
     *
     * @param scheduler:  调度器
     * @param triggerKey: 触发器，包括SimpleTrigger和CronTrigger
     * @param jobName:    任务名
     * @param jobGroup:   任务组
     * @param cron:       cron表达式
     * @param clazz:      job类
     * @Author: 亖思
     * @Date: 2023/3/22 11:37
     * @return: void
     **/
    public static void startScheduler(Scheduler scheduler,
                                      TriggerKey triggerKey,
                                      String jobName,
                                      String jobGroup,
                                      String cron,
                                      Class clazz) {
        try {
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                //创建JobDetail实例，绑定job
                JobDetail jobDetail = JobBuilder.newJob(clazz)
                        .withIdentity(jobName, jobGroup)
                        .build();

                //构建Trigger实例
                trigger = TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey)
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        //立即生效
                        .startNow()
                        .build();

                //执行
                scheduler.scheduleJob(jobDetail, trigger);
                scheduler.start();
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
